package wymiana.converters;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.primefaces.component.selectonemenu.SelectOneMenu;
import org.springframework.web.jsf.FacesContextUtils;

import wymiana.domain.School;
import wymiana.service.SchoolService;

/**
 * 
 * @author Rafal Magdon
 * @version 1.0
 * 
 *          Description:
 * 
 */
@FacesConverter(value = "schoolConverter")
public class SchoolConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		if (component instanceof SelectOneMenu) {
			String val = (String) ((SelectOneMenu) component)
					.getSubmittedValue();
			if (val != null && !"".equals(val) && val.matches("[0-9]+")) {
				return getSchoolService(context).getSchool(
						Integer.parseInt(val));
			}

		}

		return null;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		if (value instanceof School) {
			School s = (School) value;
			return s.getIdSchool().toString();
		}
		return null;
	}

	private SchoolService getSchoolService(FacesContext context) {
		return (SchoolService) FacesContextUtils.getWebApplicationContext(
				context).getBean("schoolService");
	}

}